export class PrimaryKeyManager {

    constructor(config) {
        this.config = config;
    }

    // 生成复合主键字符串
    generateCompositeKey(data) {
        return JSON.stringify(this.config.fields.map(key => data[key]));
    }

    // 解析复合主键字符串
    parseCompositeKey(compositeKey) {
        const keyObj = JSON.parse(compositeKey);

        const result = {};
        this.config.fields.forEach((field, index) => {
            result[field] = keyObj[index];
        });
        return result;
    }

    // 生成临时主键
    generateTemporaryKey() {
        const result = {};
        this.config.fields.forEach(field => {
            // result[field] = this.config.temporaryKeyStrategy[field]();
            // result[field] = `${field}_${Date.now()}`;

            // 根据field的类型（this.config.fieldTypes）生成不同的临时主键
            /*
            // 主键字段的数据类型
                fieldTypes: {
                    id: 'number',
                    name: 'string',
                    department: 'string'
                },
            */
            const fieldType = this.config.fieldTypes[field];
            if (fieldType === 'number') {
                result[field] = Date.now();
            } else if (fieldType === 'string') {
                result[field] = `${field}_${Date.now()}`;
            } else if (fieldType === 'date') {
                result[field] = new Date().toISOString().slice(0, 10);
            } else if (fieldType === 'datetime') {
                result[field] = new Date().toISOString();
            } else if (fieldType === 'boolean') {
                result[field] = false;
            }
        });
        return result;
    }

    // 验证主键唯一性
    validateUniqueness(data, existingData, excludeIndex = -1) {
        return !existingData.some((item, index) => {
            if (index === excludeIndex) return false;
            return this.config.fields.every(field => item[field] === data[field]);
        });
    }

    // 比较两个主键是否相等
    compareKeys(key1, key2) {
        return this.config.fields.every(field => key1[field] === key2[field]);
    }
}
